package com.itcoon.cloud.framework.security.utils;/**
 * @author Athric Yu
 * 2025/1/6
 **/

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.itcoon.cloud.framework.security.config.properties.JwtTokenProperties;
import com.itcoon.cloud.framework.security.model.UserPrincipal;
import com.itcoon.cloud.framework.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 *
 * @author Athric Yu
 * 2025/1/6
 **/
public class JwtTokenUtil {

    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtil.class);

    private static final JwtTokenProperties PROPERTIES = SpringUtils.getBean(JwtTokenProperties.class);

    private static final String SECRET = Base64Utils.encodeToString(PROPERTIES.getSignKey().getBytes(StandardCharsets.UTF_8));

    public static String generateAccessToken(UserPrincipal userPrincipal) {
        return JWT.create()
                .withHeader(Collections.emptyMap())
                .withClaim("id", userPrincipal.getId())
                .withClaim("username", userPrincipal.getUsername())
                .withClaim("authorities", userPrincipal.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(";")))
                .withExpiresAt(Date.from(LocalDateTime.now().plusSeconds(PROPERTIES.getTokenExpiration()).atZone(ZoneId.systemDefault()).toInstant()))
                .sign(Algorithm.HMAC256(SECRET));
    }

    public static String generateRefreshToken(String account) {
        Assert.notNull(account, "[Assertion Failure] - account is required, it must be not null");
        return JWT.create()
                .withHeader(Collections.singletonMap("type", "refresh"))
                .withClaim("account", account)
                .withExpiresAt(Date.from(LocalDateTime.now().plusSeconds(PROPERTIES.getRefreshExpiration()).atZone(ZoneId.systemDefault()).toInstant()))
                .sign(Algorithm.HMAC256(SECRET));
    }

    public static String getRealTokenFromRequest(HttpServletRequest request) {
        String token = null;
        String bearerToken = request.getHeader(PROPERTIES.getHeaderName());
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(PROPERTIES.getTokenValPrefix())) {
            token = bearerToken.substring(PROPERTIES.getTokenValPrefix().length());
        }
        return token;
    }

    private static DecodedJWT decodeToken(String token) {
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = JWT.decode(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decodedJWT;
    }

    public static Long getUserIdFromAccessToken(String token) {
        DecodedJWT decodedJWT = decodeToken(token);
        return decodedJWT.getClaim("id").asLong();
    }


    public static Authentication getAuthentication(String token) {
        DecodedJWT decodedJWT = JWT.decode(token);
        String username = decodedJWT.getClaim("username").asString();
        String authorities = decodedJWT.getClaim("authorities").asString();
        List<GrantedAuthority> grantedAuthorities = StringUtils.isEmpty(authorities) ? new ArrayList<>() : Arrays.stream(authorities.split(";")).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return new UsernamePasswordAuthenticationToken(username, null, grantedAuthorities);
    }

    public static String getAccountFromFreshToken(String refreshToken) {
        DecodedJWT decodedJWT = decodeToken(refreshToken);
        return decodedJWT.getClaim("account").asString();
    }

    public static Date getExpirationFromToken(String accessToken) {
        DecodedJWT decodedJWT = decodeToken(accessToken);
        return decodedJWT.getExpiresAt();
    }

    public static  void verifyToken(String token) {
        JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    public static String getAuthValuePrefix() {
        return PROPERTIES.getTokenValPrefix();
    }

}
